package com.itheima.servcie;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.itheima.bean.CodeBean;
import com.itheima.dbservice.QuestionServiceApi;
import com.itheima.dbservice.SettingServiceApi;
import com.itheima.dbservice.UserInfoServiceApi;
import com.itheima.dbservice.UserServiceApi;
import com.itheima.exception.CommonException;
import com.itheima.mongoservice.FriendServiceApi;
import com.itheima.mongoservice.UserLikeServiceApi;
import com.itheima.pojo.Question;
import com.itheima.pojo.Settings;
import com.itheima.pojo.UserInfo;
import com.itheima.template.OssTemplate;
import com.itheima.template.SmsTemplate;
import com.itheima.utils.ThreadLocalUtil;
import com.itheima.vo.SettingsMessageVo;
import com.itheima.vo.UserMainPage;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UsersService {
    @DubboReference
    private FriendServiceApi friendServiceApi;
    @DubboReference
    private UserLikeServiceApi userLikeServiceApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private QuestionServiceApi questionServiceApi;
    @DubboReference
    private SettingServiceApi settingServiceApi;
    @DubboReference
    private UserServiceApi userServiceApi;
    @DubboReference
    private UserInfoServiceApi userInfoServiceApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private SmsTemplate smsTemplate;

    public Boolean isAlreadyLove(Long id) {
        //获取当前登陆者id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
//        Long id = ThreadLocalUtil.getId();
        //用户查看自己自己信息默认已喜欢
        if (ObjectUtil.equal(id, uid)){
            return true;
        }
        //判断好友表里是否存在
        boolean friendExist = friendServiceApi.isFriendExist(id, uid);
        //判断喜欢表里是否存在
        boolean isLikeExist = userLikeServiceApi.getIsLikeExist(uid, id, true);
        //综合做判断
        return friendExist || isLikeExist;
    }

    /**
     * 获取设置信息
     * @return
     */
    public ResponseEntity getSettingsMessage() {
        //获取id/
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
//        Long uid  = ThreadLocalUtil.getId();

        //调用api获取陌生人问题
        Question question = questionServiceApi.getQuestion(uid);
        //获取user表中的电话号码
        String phone = userServiceApi.getPhone(uid);
        //获取通知
        Settings settings = settingServiceApi.getSettingsApi(uid);
        //创建settingsMessageVo对象
        SettingsMessageVo settingsMessageVo = new SettingsMessageVo();
        //将获取的值进行封装
        settingsMessageVo.setPhone(phone);
        settingsMessageVo.setId(Convert.toInt(question.getId()));
        settingsMessageVo.setStrangeQuestion(question.getTxt());
        settingsMessageVo.setLikeNotification(settings.getLikeNotification()==1?false:true);
        settingsMessageVo.setPinglunNotification(settings.getPinglunNotification()==1?false:true);
        settingsMessageVo.setGonggaoNotification(settings.getGonggaoNotification()==1?false:true);
        //将数据返回
        return ResponseEntity.ok(settingsMessageVo);

    }

    /**
     * 用户资料 - 更新头像
     * @param image
     * @return
     */
    public ResponseEntity updateAvatar(MultipartFile image) {
        try {
            //获取id
            Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
//            Long uid  = ThreadLocalUtil.getId();
            //上图片并获取路径
            String imagepath = ossTemplate.upload(image.getOriginalFilename(), image.getInputStream());
            //根据id获取用户详情
            UserInfo userInfo = userInfoServiceApi.getUserInfoById(uid);
            //将userInfo中的avatar更新
            userInfo.setAvatar(imagepath);
            //保存
            userInfoServiceApi.saveImagePath(userInfo);
            return ResponseEntity.ok("头像更新完成");
        } catch (IOException e) {
            throw new CommonException("上传图片失败");
        }
    }


    /**
     * 用户资料 - 保存
     * @param userInfo
     * @return
     */
    public ResponseEntity saveUserInfo(UserInfo userInfo) {
        //获取id
//        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
        Long uid  = ThreadLocalUtil.getId();
        //将结果写进userinfo
        userInfo.setId(uid);
        //更新用户表操作
        userInfoServiceApi.saveImagePath(userInfo);
        return ResponseEntity.ok("ok");
    }


    /**
     * 发送短信验证码
     * @return
     */
    public ResponseEntity sendMessage() {
        //获取id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
//        Long uid  = ThreadLocalUtil.getId();
        //获取电话号码
        String phone = userServiceApi.getPhone(uid);
        //设置rediskey
        String redisKey="changePhoneNum"+phone;
        if(!ObjectUtil.isNull(stringRedisTemplate.opsForValue().get(redisKey))){
            //验证码已发送
            return null;
        }
        //生成验证码
//        String code= RandomUtil.randomNumbers(6);
        String code= "666666";
        //执行发送短信
//        smsTemplate.sendSms(phone,stringRedisTemplate.opsForValue().get(redisKey));
        //将验证码存进redis中
        stringRedisTemplate.opsForValue().set(redisKey,code,3, TimeUnit.MINUTES);
        return ResponseEntity.ok("验证码发送成功");
    }

    /***
     * 修改手机号 - 2 校验验证码
     */
    public ResponseEntity checkCode(String phoneCode) {
        Boolean verification=false;
        //获取id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
//        Long uid  = ThreadLocalUtil.getId();
        //获取电话号码
        String phone = userServiceApi.getPhone(uid);
        //从redis中获取验证码
        String code = stringRedisTemplate.opsForValue().get("changePhoneNum" + phone);
        Map map = JSONUtil.toBean(phoneCode, Map.class);
        //校验验证码
        if (ObjectUtil.equals(map.get("verificationCode"),code)){
            //验证码校验成功
            verification=true;
        }
        //返回结果
        Map<String,Boolean> result = new HashMap<String,Boolean>();
        result.put("verification",verification);

        return ResponseEntity.ok(result);
    }
    /**
     * 修改手机号 - 3 保存
     * @param phone
     * @return
     */
    public ResponseEntity saveChangePhone(String phone) {
        //获取id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
//        Long uid  = ThreadLocalUtil.getId();
        //将redis中的验证码删除
        stringRedisTemplate.delete("changePhoneNum" + userServiceApi.getPhone(uid));
        //调用api保存修改手机号码
        userServiceApi.saveChangePhone(uid,phone);
        //返回值
        return ResponseEntity.ok("修改号码成功");
    }

    //用户资料 - 读取
    public ResponseEntity getUserInfo(Long id) {
        //判断id是否存在
        if (ObjectUtil.isNull(id)){
            id=Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
//            id  = ThreadLocalUtil.getId();
        }
        //根据id查询
        UserInfo userInfo = userInfoServiceApi.getUserInfoById(id);
        //创建返回值
        UserMainPage userMainPage = new UserMainPage();
        //复制
        UserMainPage usersMainPage = BeanUtil.copyProperties(userInfo, UserMainPage.class);
        //返回
        return ResponseEntity.ok(usersMainPage);
    }
}
